<?php
declare (strict_types=1);

namespace app\admin\model;

use app\common\model\Help as HelpModel;
use app\common\model\HelpCategory as HelpCategoryModel;

/**
 * 帮助文档模型
 * Class Help
 * @package app\admin\model
 */
class Help extends HelpModel
{
    /**
     * 获取列表
     * @param array $param
     * @return \think\Paginator
     */
    public function getList(array $param = []): \think\Paginator
    {
        // 查询参数
        $params = $this->setQueryDefaultValue($param, [
            'category_id' => -1, // 分类
            'name' => '',        // 名称
            'status' => -1,      // 状态
        ]);
        // 检索查询条件
        $filter = [];
        // 名称
        $params['category_id'] > -1 && $filter[] = ['category_ids', 'like', "%,{$params['category_id']},%"];
        // 名称
        !empty($params['name']) && $filter[] = ['name', 'like', "%{$params['name']}%"];
        // 状态
        $params['status'] > -1 && $filter[] = ['status', '=', $params['status']];
        // 查询列表数据
        return $this->field('id,category_id,category_ids,categorys,title,sort,status,create_time,update_time')->where($filter)
            ->order(['sort' => 'asc', 'create_time' => 'desc'])
            ->paginate(input('pageSize',20,'intval'));
    }
    
    /**
     * 添加新记录
     * @param $data
     * @return bool
     */
    public function add($data): bool
    {
        if(isset($data['category_id'])){
            $ids = $this->getCategoryIds($data['category_id']);
            $data['category_ids'] = ','.implode(',', $ids).',';
            $data['categorys'] = $this->getCategorys($ids);
        }
        return $this->save($data);
    }

    /**
     * 编辑记录
     * @param $data
     * @return bool
     */
    public function edit($data): bool
    {
        if(isset($data['category_id'])){
            $ids = $this->getCategoryIds($data['category_id']);
            $data['category_ids'] = ','.implode(',', $ids).',';
            $data['categorys'] = $this->getCategorys($ids);
        }
        return $this->save($data) !== false;
    }

    private function getCategoryIds(int $category_id, array $category_ids=[]): array
    {
        array_unshift($category_ids,$category_id);
        $category = HelpCategoryModel::detail($category_id);
        if($category['pid'] == 0){
            return $category_ids;
        }else{
            return $this->getCategoryIds($category['pid'], $category_ids);
        }
    }
    private function getCategorys(array $ids = []): string
    {
        $categorys = HelpCategoryModel::where('id', 'in', $ids)->column('name', 'id');
        $res = [];
        foreach ($ids as $id) {
            $res[] = $categorys[$id];
        }
        return implode(' , ', $res);
    }
}
